function [ctimes, le_ij, cle_ij, exi, exj, cex_ij]=sttimescut(jptimes, ...
                                                   cut_time) 
    
% STTIMESCUT Truncate nondecreasing sequences at a given point.
%   N nondecreasing sequences of points on the intervals [A, B_n],
%   n=1,...,N are given. Truncate the sequences at a point C, which
%   belongs to all the intervals. Add C as the last value to each
%   sequence. The sequences are stored as column vectors in a matrix. In
%   case they have different number of elements, each vector is padded
%   with its last value. 
%
% [ctimes, le_ij, cle_ij, exi, exj, cex_ij] 
%                                   = sttimescut(jptimes, cut_time)   
%
% Inputs: 
%        jptimes - a matrix of sequences stored columnwise
%        cut_time - the cut-off time
%
% Outputs:
%        ctimes - a matrix of truncated sequences
%        le_ij - indices of elements in jptimes matrix not exceeding the
%          cut-off value
%        cle_ij - indices of elements in ctimes matrix not exceeding the
%          cut-off value. The matrix has number of rows equal to maximal
%          length of the truncated sequences
%        exi - indices of rows of the elements in ctimes matrix 
%          that are padded the last value
%        exj - indices of columns of the elements in ctimes matrix 
%          that are padded the last value
%        cex_ij - indices of the elements in ctimes matrix 
%          that are padded the last value
%
% See STAIRCUT, LINJPCUT.

% Authors: R.Gaigalas, I.Kaj
% v1.0 16-Oct-05

  [njumps nproc] = size(jptimes);
             
  % find the sequence with the largest number of elements not
  % exceeding the cut-off value
  % count also the first exceeding value
  [lei, lej] = find(jptimes<cut_time);
  
  if (isempty(lei))  
    ctimes = [];
    le_ij = [];
    cle_ij = [];
    exi = [];
    exj = [];
    cex_ij = [];
    return;
  end
  
  % copy the elements satisfying the criterion
  ncut = min(max(lei)+1, njumps);           % new number of rows
  ctimes = repmat(NaN, ncut, nproc);  
  le_ij = sub2ind(size(jptimes), lei, lej); % memorize the indices
  cle_ij = sub2ind(size(ctimes), lei, lej);
  ctimes(cle_ij) = jptimes(le_ij);

  % set the exceeding elements to the cut-off time
  [exi, exj] = find(isnan(ctimes));
  cex_ij = sub2ind(size(ctimes), exi, exj); 
  ctimes(cex_ij) = cut_time;

